//
//  AddPlanViewController.m
//  FlowLayout
//
//  Created by Fuzzie Liu on 15/11/3.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "NSDate+FLCalendar.h"
#import "AddPlanViewController.h"
#import "DateCell.h"
#import "PlanCell.h"
#import "DatePickerCell.h"
#import "DietPlan.h"


#define PlanCellReuse @"PlanCell"
#define DateCellReuse @"DateCell"
#define DatePickerReuse @"DatePickerReuse"

#define RowHeight 50.0f
#define DatePickerCellHeght 220.0f

@interface AddPlanViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *myTextField;
@property (nonatomic, assign) BOOL showDatePicker;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) NSDate *date;

@end

@implementation AddPlanViewController

- (void)viewDidLoad
{
    self.title = @"添加计划";
    self.showDatePicker = NO;
    
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(addAction)];
    self.navigationItem.rightBarButtonItem = addButton;
    
    UIBarButtonItem *dismissButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    self.navigationItem.leftBarButtonItem = dismissButton;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    [self.tableView registerClass:[PlanCell class] forCellReuseIdentifier:PlanCellReuse];
    [self.tableView registerClass:[DateCell class] forCellReuseIdentifier:DateCellReuse];
    [self.tableView registerClass:[DatePickerCell class] forCellReuseIdentifier:DatePickerReuse];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        if (self.showDatePicker) {
            return 2;
        }else if (!self.showDatePicker){
            return 1;
        }
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 1) {
        return DatePickerCellHeght;
    }
    return RowHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PlanCell *cell = [tableView dequeueReusableCellWithIdentifier:PlanCellReuse forIndexPath:indexPath];
        
        self.myTextField = cell.textField;
        self.myTextField.delegate = self;
        [self.myTextField becomeFirstResponder];
        return cell;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            DateCell *cell = [tableView dequeueReusableCellWithIdentifier:DateCellReuse forIndexPath:indexPath];
            return cell;
        }else if (indexPath.row == 1){
            DatePickerCell *cell = [tableView dequeueReusableCellWithIdentifier:DatePickerReuse forIndexPath:indexPath];
            self.datePicker = cell.datePicker;
            return cell;
        }
    }
    return nil;
}
// 显示datePicker的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        static NSInteger count = 1;
        NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
            [indexSet addIndex:1];
        if (count % 2 == 1) {
            self.showDatePicker = YES;
            [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationMiddle];
        }else{
            self.showDatePicker = NO;
            [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationMiddle];
            DateCell *cell = (DateCell *)[tableView cellForRowAtIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryDetailButton;
            // 把datePicker的时间转换成系统时区的时间
//            self.date = [self.datePicker.date dateForSystemTimeZone];
            self.date = self.datePicker.date;
            cell.textField.text = [self.date stringForDate];
            NSLog(@"%@", self.date);
        }
        count++;
    }
}

- (void)addAction
{
    if ([self.myTextField.text isEqualToString:@""]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"添加失败" message:@"计划内容不能为空" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        
            
            DietPlan *newDP = [[DietPlan alloc] init];
            newDP.date = self.date;
            newDP.content = self.myTextField.text;
            [self.delegate addDietPlanWithDietPlan:newDP];
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        if ([self.datePicker.date isEqualToDate:newDP.date]) {
            
            notification.timeZone = [NSTimeZone localTimeZone];
            notification.fireDate = [newDP.date dateByAddingTimeInterval:0];
            notification.repeatInterval = kCFCalendarUnitDay;
            notification.alertBody = newDP.content;
            notification.soundName = UILocalNotificationDefaultSoundName;
//            notification.applicationIconBadgeNumber ++;
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        
            //        NSLog(@"%ld-%ld-%ld", components.year, components.month, components.day);
        }
        
    }
    [self dismissViewControllerAnimated:YES completion:nil];

}

- (void)dismiss
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated
{


}

// textField代理方法, 实现收键盘和右侧checkMark显示
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    PlanCell *cell = (PlanCell *)[textField superview];

    if (![textField.text isEqualToString:@""]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    NSLog(@"cell ======= %@", NSStringFromCGRect(textField.bounds));
    return YES;
}

@end
